const User = require('../models/User');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const axios = require('axios');

exports.register = async (req, res) => {
  const { username, password, address, contact, user_type, role } = req.body;
  try {
    const exist = await User.findOne({ where: { username } });
    if (exist) return res.status(400).json({ msg: '用户名已存在' });
    const hash = await bcrypt.hash(password, 10);
    const user = await User.create({ username, password: hash, address, contact, user_type, role });
    res.json({ msg: '注册成功', user: { id: user.id, username: user.username } });
  } catch (err) {
    res.status(500).json({ msg: '注册失败', err });
  }
};

exports.login = async (req, res) => {
  const { username, password } = req.body;
  try {
    const user = await User.findOne({ where: { username } });
    if (!user) return res.status(400).json({ msg: '用户不存在' });
    const match = await bcrypt.compare(password, user.password);
    if (!match) return res.status(400).json({ msg: '密码错误' });
    const token = jwt.sign(
      { id: user.id, role: user.role, user_type: user.user_type },
      process.env.JWT_SECRET,
      { expiresIn: '2h' }
    );
    res.json({ msg: '登录成功', token, role: user.role,user_type: user.user_type });
  } catch (err) {
    res.status(500).json({ msg: '登录失败', err });
  }
};

// 微信一键登录
exports.wxlogin = async (req, res) => {
  const { code } = req.body;
  if (!code) return res.status(400).json({ msg: '缺少code' });
  try {
    // 用 code 换 openid
    const appid = process.env.WX_APPID;
    const secret = process.env.WX_SECRET;
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
    const wxRes = await axios.get(url);
    const { openid } = wxRes.data;
    if (!openid) return res.status(400).json({ msg: '微信登录失败' });
    // 查找用户
    const user = await User.findOne({ where: { openid } });
    if (user) {
      // 已绑定，直接登录
      const token = jwt.sign(
        { id: user.id, role: user.role, user_type: user.user_type },
        process.env.JWT_SECRET,
        { expiresIn: '2h' }
      );
      return res.json({ code: 200, msg: '登录成功', token });
    } else {
      // 未绑定，返回needCategory和临时token（openid）
      return res.json({ code: 200, needCategory: true, tempToken: openid });
    }
  } catch (err) {
    res.status(500).json({ msg: '微信登录异常', err });
  }
};

// 微信绑定分类
exports.wxbindCategory = async (req, res) => {
  //  修改用户分类
  const { tempToken, categoryId } = req.body;
  try {
    const user = await User.findOne({ where: { username: tempToken } });
    if (!user) return res.status(400).json({ msg: '用户不存在' });
    user.user_type = categoryId;
    await user.save();
    res.json({ msg: '绑定成功' });
  } catch (err) {
    res.status(500).json({ msg: '绑定失败', err });
  }
};
